package com.ai.web.util;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;


public class ExportUtils {
	
	private static Logger logger = Logger.getLogger(ExportUtils.class);

	public static void export(List<Map<String, String>> dataSet, String[] keys,
			OutputStream output) {
		HSSFWorkbook book = new HSSFWorkbook();
		HSSFSheet sheet = book.createSheet();
		
		// Style the cell with borders all around.
	    CellStyle style = book.createCellStyle();
	    style.setBorderBottom(CellStyle.BORDER_THIN);
	    style.setBorderLeft(CellStyle.BORDER_THIN);
	    style.setBorderRight(CellStyle.BORDER_THIN);
	    style.setBorderTop(CellStyle.BORDER_THIN);
	    
		int k = 0;
		for (Map<String, String> mrow : dataSet) {
			HSSFRow row = sheet.createRow(k);
			k++;
			for (int i = 0; i < keys.length; ++i) {
				if (mrow.containsKey(keys[i])) {
					HSSFCell cell = row.createCell(i);
					cell.setCellValue(mrow.get(keys[i]));
					cell.setCellStyle(style);
//					logger.debug(mrow.get(keys[i]));
				}
			}
		}
		try {
			book.write(output);
			output.flush();
		} catch (Exception exp) {
			logger.error(exp.getMessage(), exp);
		}

	}
	
//	
//	public void exportCsv(List<Map<String, String>> dataSet, String[] keys,
//			OutputStream output) {
//
//		if (dataSet.size() > 1000) {
//			doCsvZipExport(dataSet, keys, output);
//		} else {
//			doCsvExport(dataSet, keys, output);
//		}
//
//	}
//
//	private void doCsvExport(List<Map<String, String>> dataSet, String[] keys,
//			OutputStream output) {
//		CsvWriter writer = null;
//		try {
//
//			writer = new CsvWriter(output, ',', Charset.forName("GBK"));
//
//			for (Map<String, String> data : dataSet) {
//				for (int i = 0; i < keys.length; ++i) {
//					if (data.containsKey(keys[i])) {
//						writer.write("=\"" + data.get(keys[i]) + "\"");
//					}
//				}
//				writer.endRecord();
//			}
//
//			writer.flush();
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//		} finally {
//			if (writer != null) {
//				writer.close();
//			}
//		}
//	}
//	
//	
//	public void doCsvZipExport(List<Map<String, String>> dataSet, String[] keys,
//			OutputStream output) {
//		
//		try {
//			CheckedOutputStream cos = new CheckedOutputStream(output,  
//			        new CRC32());  
//			ZipOutputStream out = new ZipOutputStream(cos);
//			
//			ZipEntry entry = new ZipEntry("export.csv");
//			out.putNextEntry(entry);
//			  
//			doCsvExport(dataSet, keys, out);
//		} catch (IOException e) {
//			logger.error(e.getMessage(), e);
//		}  
//		
//	}
//	

}
